import os, logging
import urllib
import random

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from app_settings   import *
from facebook_sdk   import Facebook, FacebookApiError

ROOT_PATH = os.path.dirname(__file__)
TEMPLATE = os.path.join(ROOT_PATH, 'templates')

class HomePage(webapp.RequestHandler):
    def get(self):
        logging.info('You are in get method, redirect to app')
        return self.response.out.write('<script>top.location = "%s";</script>' % app_url)

    def post(self):
        signed_request = self.request.get('signed_request', '')
        if signed_request:
            logging.debug('signed request found, load access_token')
            fb = Facebook(app_id = app_id, app_secret = app_secret)
            fb.load_signed_request(signed_request)
            if fb.access_token:
                logging.debug('access_token loaded: %s' % fb.access_token)
                try:
                    logging.debug('posting stuff...')
                    rsvp_result = fb.api(path = '/%s/attending' % event_id, 
                            method = u'POST')
                    logging.debug('getting friend ids...')
                    friends = fb.api(path = '/me/friends?fields=id')
                    self.send_random_invites(fb, get_friend_ids(friends), invite_number)
                except FacebookApiError:
                    logging.debug('operation failed!')
                    pass
                else:
                    page_path = os.path.join(TEMPLATE, 'index.html')
                    template_values = {}
                    return self.response.out.write(template.render(page_path, template_values))
            else:
                logging.error('access_token loaded unsucessfully.')
        else:
            logging.error('signed_request not found')

        #if things go wrong, it fails here
        self.reauthorize()

    def send_random_invites(self, fb, friend_ids, invite_number):
        if len(friend_ids)<invite_number:
            invite_number = length(friend_ids)
        logging.debug('sending %d random invites' % invite_number)
        ids = []
        while (invite_number>0):
            r_index = random.randint(0, len(friend_ids)-1)
            ids.append(friend_ids.pop(r_index))
            invite_number = invite_number - 1
        
        if self.send_invite(fb, ids):
            logging.debug('invite succeed!')
        else:
            logging.error('invite failed!')

    def send_invite(self, fb, ids):
        logging.debug('sending invite to %s' % id)
        params = dict(users = ','.join(ids), personal_message = invite_message) 
        return fb.api(path = '/%s/invited' % event_id, params = params, method = u'POST')

    def reauthorize(self):
        logging.debug('reauthorize')
        args = dict(client_id = app_id, redirect_uri = app_url, scope = app_scope)
        return self.response.out.write('<script>top.location = "%s";</script>' % 
                ("https://graph.facebook.com/oauth/authorize?" + urllib.urlencode(args)))

def get_friend_ids(friends):
    friend_ids = []
    logging.debug('getting friend ids')
    for friend in friends['data']:
        friend_ids.append(friend.get('id'))

    return friend_ids

routes = [
        ('/', HomePage),
        ]
application = webapp.WSGIApplication(routes, debug=False)

def main():
    #logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
